package com.neusoft.bizcore.notice.notification.factory.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.notice.constant.NoticeConsts;
import com.neusoft.bizcore.notice.notification.dto.NoticeRecordDTO;
import com.neusoft.bizcore.notice.notification.dto.NoticeRecordSystemDTO;
import com.neusoft.bizcore.notice.notification.factory.MessageFactory;
import com.neusoft.bizcore.notice.notification.model.enums.SendStatus;
import com.neusoft.bizcore.notice.system.dto.SystemNoticeDTO;
import com.neusoft.bizcore.notice.system.service.SystemNoticeService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class NoticeMessageFactory implements MessageFactory {

    @Autowired
    private SystemNoticeService systemNoticeService;

    @Override
    public void sendMessage(final NoticeRecordDTO msg) {
        NoticeMessageFactory.log.info("系统通知消息 发送开始----------");
        NoticeRecordSystemDTO sys = msg.getSystem();
        String status = SendStatus.success.toString();
        String errorMsg = NoticeConsts.INFORM_TYPE_NOTICE + NoticeConsts.NOTICE_SEND_SUCCESS;
        try {
            if ((sys != null) && (sys.getUsers() != null) && !sys.getUsers().isEmpty()) {
                final SystemNoticeDTO dto = new SystemNoticeDTO();
                dto.setAppCode(msg.getAppCode());
                dto.setBusinessInfo(sys.getBusinessInfo());
                dto.setContent(sys.getContent());
                dto.setNoticeType(sys.getNoticeType());
                dto.setNoticeRoute(sys.getNoticeRoute());
                dto.setTitle(msg.getTitle());
                dto.setUserId(sys.getUsers());
                this.systemNoticeService.create(dto);
                NoticeMessageFactory.log.info(errorMsg);

            } else {
                status = SendStatus.failure.toString();
            }
        } catch (final Exception e) {
            status = SendStatus.failure.toString();
            errorMsg = NoticeConsts.INFORM_TYPE_NOTICE + NoticeConsts.NOTICE_SEND_FAILURE + " : " + e.getMessage();
            NoticeMessageFactory.log.info(errorMsg, e);
        } finally {
            if (sys == null) {
                sys = new NoticeRecordSystemDTO();
                msg.setSystem(sys);
                errorMsg =
                        NoticeConsts.INFORM_TYPE_NOTICE + NoticeConsts.NOTICE_SEND_FAILURE + NoticeConsts.NOTICE_NO_MSG;
            } else if ((sys.getUsers() == null) || sys.getUsers().isEmpty()) {
                errorMsg =
                        NoticeConsts.INFORM_TYPE_NOTICE + NoticeConsts.NOTICE_SEND_FAILURE
                                + NoticeConsts.NOTICE_NO_MAIL_RECEIVER;
            }
            sys.setStatus(status);
            sys.setErrorMsg(errorMsg);
            NoticeMessageFactory.log.info("系统通知消息 发送结束----------");
        }
    }

}
